import flash.display.*;
import flash.events.*;
import flash.net.URLRequest;
import flash.text.*;
import flash.utils.Timer;
import mx.controls.*;
import mx.core.*;

import Game;
import Round;

import projectile.Waterballoon;
import techquest.DataPoster;
import techquest.Physics;
import techquest.Velocity;

private function init():void 
{
	// var background:UIComponent = new UIComponent();
	var balloon:Waterballoon = new Waterballoon(); 
	var drop:UIComponent = new UIComponent(); 
	var monkey:UIComponent = new UIComponent();
	var targetMonkey:UIComponent = new UIComponent();
	var slingHandle:UIComponent = new UIComponent();
	var slingPouch:UIComponent = new UIComponent();
	var gameStage:UIComponent = new UIComponent(); 
	var line:UIComponent = new UIComponent();
	var line2:UIComponent = new UIComponent();
	var distanceLine:UIComponent = new UIComponent();
	var movementLayer:UIComponent = new UIComponent();
	var background:UIComponent = new UIComponent();
	var tf:TextField = new TextField();
	var tfDistance:TextField = new TextField();
	var tfForce:TextField = new TextField();
	var timeInMotion:Number;
	var trajectory:Number;
	var force:Number;
	var mass:Number = 0.325;

	var pictLdr:Loader = new Loader();
	var pictURL:String = "assets/background.swf"
	var pictURLReq:URLRequest = new URLRequest(pictURL);
	pictLdr.load(pictURLReq);
	// Once the image is done loading then
	pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
	function imgLoaded(e:Event):void
	{

		background.addChild(pictLdr.content);

		// size the background to be the size of the application
		background.height = main.height;
		background.width = main.width;
		background.getChildAt(0).height = main.height;
		background.getChildAt(0).width = main.width;

		main.addChild(background);
		// background.stage.displayState = flash.display.StageDisplayState.FULL_SCREEN;
	}


	var balloonLdr:Loader = new Loader();
	var balloonURL:String = "assets/balloon.swf"
	var balloonURLReq:URLRequest = new URLRequest(balloonURL);
	balloonLdr.load(balloonURLReq);

	// Once the image is done loading then
	balloonLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, balloonLoaded);
	function balloonLoaded(e:Event):void
	{
		balloon.addChild( balloonLdr.content );
		// gameStage.addChild( balloonLdr.content );
		// balloon.getChildAt(0).move(100,100);
		// balloon.alpha = 0;
		// balloonLdr.content.scaleX = 40;
		// balloonLdr.content.scaleY = 40;
		balloon.getChildAt(0).scaleX = .40;
		balloon.getChildAt(0).scaleY = .40;
	}

	var dropLdr:Loader = new Loader();
	var dropURL:String = "assets/drop.swf"
	var dropURLReq:URLRequest = new URLRequest(dropURL);
	dropLdr.load(dropURLReq);

	// Once the image is done loading then
	dropLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, dropLoaded);
	function dropLoaded(e:Event):void
	{
		drop.addChild( dropLdr.content );
		drop.scaleX = .2;
		drop.scaleY = .2;
	}


	var monkeyLdr:Loader = new Loader();
	var monkeyURL:String = "assets/monkey.swf"
		var monkeyURLReq:URLRequest = new URLRequest(monkeyURL);
	monkeyLdr.load(monkeyURLReq);

	// Once the image is done loading then
	monkeyLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, monkeyLoaded);
	function monkeyLoaded(e:Event):void
	{
		// add the first monkey, which is for the player
		monkey.addChild( monkeyLdr.content );
		monkey.x = 100;
		monkey.y = 400;
		monkey.scaleX = .80;
		monkey.scaleY = .80;
	}

	var targetLdr:Loader = new Loader();
	var targetURL:String = "assets/monkey.swf"
		var targetURLReq:URLRequest = new URLRequest(targetURL);
	targetLdr.load(targetURLReq);

	// Once the image is done loading then
	targetLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, targetLoaded);
	function targetLoaded(e:Event):void
	{
		// add the second monkey which serves as the target.
		targetMonkey.addChild(targetLdr.content);
		targetMonkey.x = 500 + Math.random()*200;
		targetMonkey.y = 400;
		targetMonkey.scaleX = -0.80;
		targetMonkey.scaleY = 0.80;
	}

	var slingHandleLdr:Loader = new Loader();
	var slingHandleURL:String = "assets/slingHandle.swf"
		var slingHandleURLReq:URLRequest = new URLRequest(slingHandleURL);
	slingHandleLdr.load(slingHandleURLReq);

	// Once the image is done loading then
	slingHandleLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, slingHandleLoaded);
	function slingHandleLoaded(e:Event):void
	{
		slingHandle.addChild( slingHandleLdr.content );
		slingHandle.x = 120;
		slingHandle.y = 350;
		slingHandle.scaleX = .80;
		slingHandle.scaleY = .80;
	}

	var slingPouchLdr:Loader = new Loader();
	var slingPouchURL:String = "assets/slingPouch.swf"
	var slingPouchURLReq:URLRequest = new URLRequest(slingPouchURL);
	slingPouchLdr.load(slingPouchURLReq);

	// Once the image is done loading then
	slingPouchLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, slingPouchLoaded);
	function slingPouchLoaded(e:Event):void
	{
		slingPouch.addChild( slingPouchLdr.content );
		slingPouch.x = 120;
		slingPouch.y = 350;
		slingPouch.scaleX = .80;
		slingPouch.scaleY = .80;
	}

	// The following is a nasty little work around to get
	// the monkey to appear in front of the background
	// it appears that the events that load the images
	// are not executed conesecutively so this code will
	// use a timer to add the monkey to the stage 200ms later
	// it works, but it is still nasty - [Clark]
	var myTimer:Timer = new Timer(200,1); // set to go off in 1 second
	myTimer.addEventListener(TimerEvent.TIMER, addMonkey);
	myTimer.start();

	function addMonkey(e:TimerEvent):void 
	{
		var format: TextFormat = new TextFormat();

		main.addChild(monkey);
		main.addChild(targetMonkey);
		main.addChild(slingHandle);
		main.addChild(gameStage);
		main.addChild(slingPouch);

		// add text in
		tf.text = "Welcome to Balloon.  Balloons Remaining: " + String(Game.ROUNDS_PER_GAME - Game.currentRound );
		tf.autoSize = TextFieldAutoSize.LEFT;
		gameStage.addChild(tf);

		tfForce.text = "F = ";
		tfForce.autoSize = TextFieldAutoSize.LEFT;
		format.size = 24;
		format.color = 0xFF0000;
		tfForce.setTextFormat(format);
		gameStage.addChild(tfForce);
		tfForce.x = monkey.x;
		tfForce.y = monkey.y - 100;

		tfDistance.text = "Welcome to Balloon.  Balloons Remaining: " + String(Game.ROUNDS_PER_GAME - Game.currentRound - 1);
		tfDistance.autoSize = TextFieldAutoSize.CENTER;
		gameStage.addChild(tfDistance);
		tfDistance.x = monkey.x;// + ( targetMonkey.x - monkey.x ) / 2;
		tfDistance.width = targetMonkey.x - monkey.x;
		tfDistance.y = background.height - background.height * 0.05;//monkey.y + monkey.measuredHeight + (monkey.measuredHeight / 4);
		var distance:Number = (targetMonkey.x - monkey.x)/10;
		tfDistance.text = "Distance to Target: " + distance.toFixed(1) + " meters";

		gameStage.graphics.lineStyle(10,0xBFD7EE);
		gameStage.graphics.moveTo(monkey.x ,monkey.getBounds( gameStage ).bottom);
		gameStage.graphics.lineTo(targetMonkey.x, monkey.getBounds( gameStage ).bottom);


	}


	// BEGIN CLARK CODE - It's BACON!!!!

	//
	// FIGLEAF SOFTWARE RGB to Hex
	function rgbToHex(r:int, g:int, b:int):int 
	{
		return (r << 16 | g << 8 | b);
	}

	/* global variables */
	var pos_x:Number = 0;
	var pos_y:Number = 0;
	var vel_rot:Number = 0;
	var mouse_down:Boolean = false;
	var start_x:Number = 0;
	var start_y:Number = 0;

	// Add a handler for the MOUSE_DOWN event
	slingPouch.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
	function downHandler(event:MouseEvent):void
	{
		if(Game.currentRound < 6)
			mouse_down = true;
		start_x = slingPouch.x;
		start_y = slingPouch.y;
	}


	// Add a handler for the MOUSE_MOVE event
	slingPouch.addEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
	main.addEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
	function moveHandler(event:MouseEvent):void
	{
		if (mouse_down) 
		{
			// drawgameStage();
			gameStage.graphics.clear();
			gameStage.graphics.lineStyle(10,0xBFD7EE);
			gameStage.graphics.moveTo(monkey.x ,monkey.getBounds( gameStage ).bottom+10);
			gameStage.graphics.lineTo(targetMonkey.x, monkey.getBounds( gameStage ).bottom+10);


			gameStage.graphics.lineStyle(10,0xBFD7EE);
			gameStage.graphics.moveTo(start_x,start_y);
			gameStage.graphics.lineTo(event.stageX, event.stageY);
			slingPouch.x = event.stageX+10;
			slingPouch.y = event.stageY-15;
			if(slingPouch.x > slingHandle.x)
				slingPouch.x = slingHandle.x;

			drawSlingString();

		var angle:Number;
		var forceX:Number;
		var forceY:Number;
		forceX = (start_x-slingPouch.x)/2;
		forceY = (start_y-slingPouch.y)/2;
		
		angle = Math.atan2(forceY, forceX);
		if(angle < 0)
			angle = 2 * Math.PI + angle;

		trajectory = 360 - angle * 180 / Math.PI;

		// vel_rot is for the angular rotation of the balloon
		var format: TextFormat = new TextFormat();
		force = vel_rot = Math.sqrt(forceX * forceX + forceY * forceY);
		tfForce.text = "F = "+force.toFixed(1)+"N  \nAngle: "+trajectory.toFixed(1)+" degrees";
		equation.text = force.toFixed(1) + "N = " + mass.toFixed(3) + "kg * " + (force/mass).toFixed(2) + "m/s^2";
		format.size = 24;
		format.color = 0xFF0000;
		tfForce.setTextFormat(format);

		}
	}


	// Add a handler for the MOUSE_UP event
	main.addEventListener(MouseEvent.MOUSE_UP, upHandler);
	function upHandler(event:MouseEvent):void
	{
		if(mouse_down == false)
			return;
		var scale:Number = 40;
		var angle:Number;
		var velocity:Velocity = new Velocity();
		var forceX:Number;
		var forceY:Number;
		var physics:Physics = new Physics();

		// pos_x and pos_y will be the initial position for
		// the balloon once it launches
		pos_x = start_x;
		pos_y = start_y;

		// the x and y velocities are determined by the slope
		// of the line and then divided by 5 to scale it down
		// a bit.
		forceX = (start_x-slingPouch.x)/2;
		forceY = (start_y-slingPouch.y)/2;

		angle = Math.atan2(forceY, forceX);
		if(angle < 0)
			angle = 2 * Math.PI + angle;

		trajectory = 360 - angle * 180 / Math.PI;
		// vel_rot is for the angular rotation of the balloon
		force = vel_rot = Math.sqrt(forceX * forceX + forceY * forceY);

		// if vel_x is negative then rotation will be the
		// other direction.
		if(velocity.velocityX < 0)
			vel_rot = -vel_rot;

		trace("Force="+force+" Fx="+forceX+" Fy="+forceY);
		velocity = physics.getInitialVelocities(force, mass, angle);
		if(forceY < 0)
			velocity.velocityY = -velocity.velocityY;

		trace("Vx="+velocity.velocityX);
		trace("Vy="+velocity.velocityY);
		balloon.setVelocity(velocity);
		mouse_down = false;
		gameStage.graphics.clear();
		gameStage.graphics.lineStyle(10,0xBFD7EE);
		gameStage.graphics.moveTo(monkey.x ,monkey.getBounds( gameStage ).bottom+10);
		gameStage.graphics.lineTo(targetMonkey.x, monkey.getBounds( gameStage ).bottom+10);


		balloon.x = pos_x;
		balloon.y = pos_y;
		balloon.visible = true;
		gameStage.addChild( balloon );
		slingPouch.x = 120;
		slingPouch.y = 350;

		timeInMotion = 0;

		tf.text = "Time (t) = " + timeInMotion.toFixed(1) + " Balloons Remaining: " + String(Game.ROUNDS_PER_GAME - Game.currentRound - 1);
	}

	balloon.addEventListener(Event.ENTER_FRAME, moveBalloon);
	function moveBalloon(e:Event):void
	{
		if(gameStage.contains( balloon )) {
			var velocity:Velocity = balloon.getVelocity();
			var physics:Physics = new Physics();
			var delta_t:Number = 0.5;

			// check to see if balloon hit the ground
			if( balloon.y > monkey.y + monkey.height ) {
				velocity.velocityX = velocity.velocityY = 0;
				balloon.setVelocity(velocity);
				// change graphic to a splash
				if( gameStage.contains( balloon ) )
					gameStage.removeChild(balloon);
				drop.x = balloon.x;
				drop.y = balloon.y;
				if( balloon.x < background.width )
					gameStage.addChild(drop);
				nextRound(false);

			}// check to see if the balloon hit the target
			else if(balloon.hitTestObject(targetMonkey))
			{
				//		trace("Greate Success!");
				velocity.velocityX = velocity.velocityY = 0;
				balloon.setVelocity(velocity);
				// change graphic to a splash
				if( gameStage.contains( balloon ) )
					gameStage.removeChild(balloon);
				drop.x = balloon.x;
				drop.y = balloon.y;
				gameStage.addChild(drop);
				nextRound(true);
			} else if ( balloon.x > background.width || balloon.x < 0 ){
				// check to see if balloon exited playground
				// change graphic to a splash
				//if( gameStage.contains( balloon ) )
				//	gameStage.removeChild(balloon);
				balloon.visible = false;

			}

			if(velocity.velocityY != 0 || velocity.velocityX != 0)
			{
				velocity.velocityY = physics.updateYVelocity(velocity.velocityY, delta_t);
				timeInMotion += delta_t;
				tf.text = "Time (t) = " + timeInMotion.toFixed(1) + " sec   Balloons Remaining: " + String(Game.ROUNDS_PER_GAME - Game.currentRound - 1);
				balloon.x += physics.getChangeInXDistance(velocity.velocityX, delta_t);
				balloon.y += physics.getChangeInYDistance(velocity.velocityY, delta_t);
				balloon.setVelocity(velocity);
			}
		}
	}

	function nextRound( hit:Boolean ):void
	{
		// we essentially have all the information we need to end the round so
		// store the data
		var round:Round = new Round();
		round.acceleration = 10; // TODO add the acceleration here
		round.distance = balloon.x - monkey.x; // the distance away from the character
		// that the balloon hits
		round.distanceToTarget = targetMonkey.x - monkey.x;
		round.force = force;
		round.hit = hit; 
		round.mass = 10; // TODO add the mass that the user picks here
		round.timeUntilLaunch = 10; // TODO
		if( Game.advanceToNextRound( round ) ) {
			// GAME OVER CODE HERE
		}
	}

	function drawSlingString():void
	{
		var X:Number = slingPouch.x;
		var Y:Number = slingPouch.y;

		if(X > slingHandle.x)
			X = slingHandle.x;

		gameStage.graphics.clear();
		gameStage.graphics.lineStyle(10,0xBFD7EE);
		gameStage.graphics.moveTo(monkey.x ,monkey.getBounds( gameStage ).bottom+10 );
		gameStage.graphics.lineTo(targetMonkey.x, monkey.getBounds( gameStage ).bottom+10);


		gameStage.graphics.lineStyle(5,0xBFD7EE, 127);
		gameStage.graphics.lineGradientStyle("linear", [0xFF7E00,0xFFFF00],[255,255],[0,255]);

		gameStage.graphics.moveTo(slingHandle.x+7, slingHandle.y-10);
		gameStage.graphics.lineTo(X+7, Y);

		gameStage.graphics.moveTo(slingHandle.x-25, slingHandle.y-17);
		gameStage.graphics.lineTo(X-30, Y);

	}
        			        
	// END CLARK CODE - YEAH BABY!!! //
}

